package com.cykj.web.controller.posbiz;

import com.cykj.common.annotation.Log;
import com.cykj.common.core.controller.BaseController;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.core.page.TableDataInfo;
import com.cykj.common.enums.BusinessType;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.common.utils.StringUtils;
import com.cykj.common.utils.poi.ExcelUtil;
import com.cykj.pos.domain.BizAgentOpenAccount;
import com.cykj.pos.domain.BizMerchant;
import com.cykj.pos.domain.BizMicroInfo;
import com.cykj.pos.domain.BizWallet;
import com.cykj.pos.domain.dto.BizMerchantReturnMoneyDTO;
import com.cykj.pos.domain.dto.UseRegistrationDTO;
import com.cykj.pos.mapper.BizMerchantMapper;
import com.cykj.pos.mapper.BizUserAccountMapper;
import com.cykj.pos.service.*;
import com.cykj.pos.util.BigDecimalUtil;
import com.cykj.pos.util.DESHelperUtil;
import com.cykj.pos.util.UUIDUtil;
import com.cykj.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * 1、统一商户入件Controller
 *
 * @author weijianbo
 * @date 2021-09-01
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/pos/entry" )
public class BizUserAccountController extends BaseController {

    @Autowired
    private IBizUserAccountService bizUserAccountService;
    @Autowired
    private IBizMerchantService iBizMerchantService;

    @Autowired
    private BizUserAccountMapper bizUserAccountMapper;
    @Autowired
    private IBizWalletService walletService;
    @Autowired
    private IBizMicroInfoService iBizMicroInfoService;
    @Autowired
    private IBizAgentOpenAccountService iBizAgentOpenAccountService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private BizMerchantMapper bizMerchantMapper;

    /**
     * @author: haoran
     * @date: 2022/7/29
     * 方法名称： 代理管理列表查询
     */
    @PreAuthorize("@ss.hasPermi('system:entry:list')")
    @GetMapping("/list")
    public TableDataInfo list(UseRegistrationDTO useRegistrationDTO)
    {
        startPage();
        List<UseRegistrationDTO> list = bizUserAccountService.selectBizUserAccountList(useRegistrationDTO);
        return getDataTable(list);
    }
    /*过滤设置*/
    @GetMapping("/list/filtration")
    public TableDataInfo filtrationList(UseRegistrationDTO useRegistrationDTO)
    {
        if ( useRegistrationDTO.getParentId()==null){
            SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
            if (sysUserman.getUserId()==1l){
                useRegistrationDTO.setUserId(2l);
            }else {
                useRegistrationDTO.setUserId(sysUserman.getUserId());
            }
        }else {
            //查询  userId
            Long userId= bizUserAccountMapper.selectUserId(Long.valueOf(useRegistrationDTO.getParentId()));
            useRegistrationDTO.setUserId(userId);
            useRegistrationDTO.setNode(1);
        }
        startPage();
        List<UseRegistrationDTO> list = bizUserAccountService.filtrationList(useRegistrationDTO);
        return getDataTable(list);
    }

    /**
     * 导出1、统一商户入件列表
     */
    @PreAuthorize("@ss.hasPermi('system:entry:export')")
    @Log(title = "1、统一商户入件", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(UseRegistrationDTO useRegistrationDTO)
    {
        List<UseRegistrationDTO> list = bizUserAccountService.exportBizUserAccountList(useRegistrationDTO);
        ExcelUtil<UseRegistrationDTO> util = new ExcelUtil<UseRegistrationDTO>(UseRegistrationDTO.class);
        return util.exportExcel(list, "entry");
    }

    /**
     * 获取1、统一商户入件详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:entry:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(bizUserAccountService.selectBizUserAccountById(id));
    }

    //设置详情
    @GetMapping(value = "/set/{id}")
    public AjaxResult getSetInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(bizUserAccountService.selectBizUserSetId(id));
    }

    /**
     * 新增1、统一商户入件
     */
    @PreAuthorize("@ss.hasPermi('system:entry:add')")
    @Log(title = "1、统一商户入件", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody UseRegistrationDTO useRegistrationDTO)
    {
        SysUser sysUser=new SysUser();
        sysUser.setUserName(useRegistrationDTO.getPhonenumber());// 电话号为登录账号
        sysUser.setPassword("$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2");
        BizAgentOpenAccount bizAgentOpenAccount=new BizAgentOpenAccount();
        /*生成uuid*/
        String uuid=UUIDUtil.getUUID();
        bizAgentOpenAccount.setParentUserId(uuid);
        bizAgentOpenAccount.setQrsettleRate(useRegistrationDTO.getNamesm());
        bizAgentOpenAccount.setRatet0(useRegistrationDTO.getNamesk());
        bizAgentOpenAccount.setPlusThree((useRegistrationDTO.getPlusThree() ==null || "".equals(useRegistrationDTO.getPlusThree()))?"0":useRegistrationDTO.getPlusThree());
        /*插入套餐*/
        bizUserAccountService.insertBizAccount(bizAgentOpenAccount);
        /*获取account_id*/
        int accountId=iBizAgentOpenAccountService.selectaccount(uuid);
        /*插入user*/
        sysUser.setNickName(useRegistrationDTO.getNickName());
        sysUser.setPhonenumber(useRegistrationDTO.getPhonenumber());
        sysUser.setAccountId(String.valueOf(accountId));
        sysUser.setInviteUserId(Long.valueOf(useRegistrationDTO.getMerchName()));
        sysUser.setCreateBy(useRegistrationDTO.getMerchName());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        int rows=bizUserAccountService.insertBizUser(sysUser);
        SysUser user = iSysUserService.getSysUserByPhonenumber(useRegistrationDTO.getPhonenumber());
        /*插入合作伙伴*/
        BizMerchant parent = iBizMerchantService.getMerchantByUserId(Long.valueOf(useRegistrationDTO.getMerchName()));
        System.out.println(useRegistrationDTO);
        BizMerchant bizMerchant =new BizMerchant();
        String merchName=useRegistrationDTO.getNickName();
        bizMerchant.setMerchName(merchName);
        bizMerchant.setUserId(user.getUserId());
        bizMerchant.setParentId(parent.getMerchId());
        String code = iBizMerchantService.generateMerchCode("SLM");
        bizMerchant.setMerchCode(code);
        bizMerchant.setMerchRegion("吉林省");
        bizMerchant.setMerchAddr("长春");
        Date date=new Date();
        bizMerchant.setCreateTime(date);
        bizMerchant.setUpdateTime(date);
        /*查询merch_id*/
        iBizMerchantService.insertMerchant(bizMerchant);
        Long merchId= Long.valueOf(iBizMerchantService.selectMerchIdadd(String.valueOf(useRegistrationDTO.getNickName())));
        /*插入到个人信息*/
        BizMicroInfo bizMicroInfo=new BizMicroInfo();
        bizMicroInfo.setMerchIdcardName(useRegistrationDTO.getNickName());
        bizMicroInfo.setMerchBankMobile(useRegistrationDTO.getPhonenumber());
        bizMicroInfo.setMerchId(merchId);
        bizMicroInfo.setMerchBank("吉林银行");
        bizMicroInfo.setMerchBankCardno("6210810940009496552");
        bizMicroInfo.setMerchBankCity("吉林省长春市");
        bizMicroInfo.setMerchBankCard("https://cykj-1303987307.cos.ap-beijing.myqcloud.com/authentication/220181198501064418/20210209/352486619.jpg");
        bizMicroInfo.setMerchIdcardPositive("https://cykj-1303987307.cos.ap-beijing.myqcloud.com/authentication/220181198501064418/20210209/1746315680.jpg");
        bizMicroInfo.setMerchIdcardBack("https://cykj-1303987307.cos.ap-beijing.myqcloud.com/authentication/220181198501064418/20210209/1304699226.jpg");
        bizMicroInfo.setMerchIdcard("220181198501064418");
        bizMicroInfo.setMerchIdcardDuedate("2015.09.03-2035.09.03");
        bizMicroInfo.setCreateTime(new Date());
        bizMicroInfo.setUpdateTime(new Date());
        iBizMicroInfoService.save(bizMicroInfo);

        String amount_money = BigDecimalUtil.getString(0.0); // 结算账户总额
        String secretKey = DESHelperUtil.getSecretKey();
        String secretMoney = DESHelperUtil.encrypt(secretKey,amount_money);
        BizWallet wallet = new BizWallet();
        wallet.setProfitAmount(secretMoney);
        wallet.setRewardAmount(secretMoney);
        wallet.setWalletAmount(secretMoney);
        wallet.setSecretKey(secretKey);
        // 通用积分  活动积分
        Long integral = 0L;
        String secretIntegral = DESHelperUtil.encrypt(secretKey,String.valueOf(integral));
        // 设置积分
        wallet.setIntegral(secretIntegral); // 通用积分
        wallet.setActivityIntegral(secretIntegral);// 活动积分
        wallet.setUserId(user.getUserId());
        walletService.save(wallet);
        bizMerchantMapper.generateAllMerchParentRelated();
        //bizMerchantMapper.generateAllPosMerchParentRelated();
        return toAjax(rows);
    }

    /**
     * 修改1、统一商户入件
     */
    @PreAuthorize("@ss.hasPermi('system:entry:edit')")
    @Log(title = "代理列表修改", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    @Transactional
    public AjaxResult edit(@RequestBody UseRegistrationDTO useRegistrationDTO)
    {
        String msg="修改成功";
      if(useRegistrationDTO.getIsclicka().equals("a") && !useRegistrationDTO.getIsclicka().equals("")){
        useRegistrationDTO.setMerchName(useRegistrationDTO.getNickMerchName());
      }else {
        useRegistrationDTO.setMerchName(useRegistrationDTO.getParentUserId());
      }
          if(useRegistrationDTO.getIsclickb().equals("b") && !useRegistrationDTO.getIsclickb().equals("")){
              useRegistrationDTO.setNamesm(useRegistrationDTO.getNamesm());
          }else {
              useRegistrationDTO.setNamesm(useRegistrationDTO.getQrsettleRate());
          }
      if(useRegistrationDTO.getIsclickc().equals("c")  && !useRegistrationDTO.getIsclickc().equals("")){
        useRegistrationDTO.setNamesk(useRegistrationDTO.getNamesk());
      }else {
        useRegistrationDTO.setNamesk(useRegistrationDTO.getRatet0());
      }
        SysUser sysUser=new SysUser();
        sysUser.setPassword(SecurityUtils.encryptPassword("666666"));//密码
        sysUser.setUserName(useRegistrationDTO.getPhonenumber());//电话号
        sysUser.setPhonenumber(useRegistrationDTO.getPhonenumber());//电话号
        String nickName=useRegistrationDTO.getNickName();//名字
        sysUser.setNickName(nickName);
        SysUser parentUser=bizMerchantMapper.selectParentMerchByUserIds(useRegistrationDTO.getUserId());
        if(parentUser.getRate().compareTo(useRegistrationDTO.getRate())<=0){
            sysUser.setRate(useRegistrationDTO.getRate());
        }else{
            msg="税点修改失败，税点必须大于等于上级税点！";
        }

        sysUser.setServiceCharge(useRegistrationDTO.getServiceCharge());
        sysUser.setCreateBy(useRegistrationDTO.getMerchName());//上级id

        sysUser.setInviteUserId(Long.valueOf(useRegistrationDTO.getMerchName()));//上级id

        sysUser.setUserId(useRegistrationDTO.getUserId());
        sysUser.setWithdraw(Integer.parseInt(useRegistrationDTO.getWithdraw()));
        bizUserAccountService.updateBizUser(sysUser);
        BizAgentOpenAccount bizAgentOpenAccount=new BizAgentOpenAccount();
        /*生成uuid*/
        Long accountId=iSysUserService.selectAccountIds(useRegistrationDTO.getUserId());//通过userid获取account_id
        Long merchId= Long.valueOf(iBizMerchantService.selectMerchId(String.valueOf(useRegistrationDTO.getUserId())));//查询伙伴merch_id
        /*套餐*/
        bizAgentOpenAccount.setAccountId(accountId);//account_id
        bizAgentOpenAccount.setQrsettleRate(useRegistrationDTO.getNamesm());//扫码
        bizAgentOpenAccount.setRatet0(useRegistrationDTO.getNamesk());//刷卡
        BizMicroInfo bizMicroInfo=new BizMicroInfo();
        bizMicroInfo.setMerchIdcardName(useRegistrationDTO.getNickName());//姓名
        bizMicroInfo.setMerchBankMobile(useRegistrationDTO.getPhonenumber());//电话号码
        bizMicroInfo.setMerchId(merchId);//merchid
        iBizMicroInfoService.updataMicroInfo(bizMicroInfo);//修改个人信息
        /*合作伙伴*/
        BizMerchant bizMerchant =new BizMerchant();
        String merchName=useRegistrationDTO.getNickName();//姓名
        bizMerchant.setMerchName(merchName);//姓名
        bizMerchant.setUserId(useRegistrationDTO.getUserId());//userId
        BizMerchant parent = iBizMerchantService.getMerchantparentId(Long.valueOf(useRegistrationDTO.getMerchName()));
        bizMerchant.setParentId(parent.getMerchId());//上级id
        /*查询merch_id*/
        iBizMerchantService.updataMerchant(bizMerchant);//修改合作伙伴
        bizMerchantMapper.generateAllMerchParentRelated();
        //bizMerchantMapper.generateAllPosMerchParentRelated();
        if(StringUtils.isNotBlank(msg)&&!"修改成功".equals(msg)){
            return AjaxResult.success(msg);
        }
        return toAjax(bizUserAccountService.updateBizAccount(bizAgentOpenAccount));
    }

    @Log(title = "代理列表设置", businessType = BusinessType.UPDATE)
    @PutMapping("/updateSet")
    @Transactional
    public AjaxResult editSet(@RequestBody UseRegistrationDTO useRegistrationDTO)
    {
        BizAgentOpenAccount bizAgentOpenAccount=new BizAgentOpenAccount();
        /*套餐*/
        bizAgentOpenAccount.setAccountId(useRegistrationDTO.getAccountId());//account_id
        bizAgentOpenAccount.setServerTwoFour(useRegistrationDTO.getServerTwoFour());//服务费返现36档
        bizAgentOpenAccount.setServerThirtySix(useRegistrationDTO.getServerThirtySix());//服务费返现36档
        bizAgentOpenAccount.setServerFortyEight(useRegistrationDTO.getServerFortyEight());//服务费返现49档
        bizAgentOpenAccount.setServerFortyNine(useRegistrationDTO.getServerFortyNine());//服务费返现48档

        bizAgentOpenAccount.setServerSixty(useRegistrationDTO.getServerSixty());//服务费返现60档
        bizAgentOpenAccount.setServerNinetyNine(useRegistrationDTO.getServerNinetyNine());//服务费返现99档
        bizAgentOpenAccount.setServerOneNinetyNine(useRegistrationDTO.getServerOneNinetyNine());//服务费返现199档
        bizAgentOpenAccount.setServerTwoNinetyNine(useRegistrationDTO.getServerTwoNinetyNine());//服务费返现299档
        bizAgentOpenAccount.setServerThreeNinetyNine(useRegistrationDTO.getServerThreeNinetyNine());//服务费返现299档
        bizAgentOpenAccount.setFlowTwoFour(useRegistrationDTO.getFlowTwoFour());//流量费返现24档
        bizAgentOpenAccount.setFlowThirtySix(useRegistrationDTO.getFlowThirtySix());//流量费返现36档
        bizAgentOpenAccount.setFlowFortyEight(useRegistrationDTO.getFlowFortyEight());//流量费返现48档
        bizAgentOpenAccount.setFlowSixty(useRegistrationDTO.getFlowSixty());//流量费返现60档
        bizAgentOpenAccount.setFlowSixtyLkl(useRegistrationDTO.getFlowSixtyLkl());//流量费返现60档
        bizAgentOpenAccount.setFlowSixtyHyb(useRegistrationDTO.getFlowSixtyHyb());//流量费返现60档
        bizAgentOpenAccount.setFlowNinetyNine(useRegistrationDTO.getFlowNinetyNine());//流量费返现99档
        bizAgentOpenAccount.setServerSwitch(useRegistrationDTO.getServerSwitch());//费用收取开关  1 开     0 关
        bizAgentOpenAccount.setPlusThree(useRegistrationDTO.getPlusThree());//
        bizAgentOpenAccount.setFlowSixtyEight(useRegistrationDTO.getFlowSixtyEight());//68
        bizAgentOpenAccount.setFlowSeventySeven(useRegistrationDTO.getFlowSeventySeven());//77
        if(Double.parseDouble(useRegistrationDTO.getPlusThree()) > 3){
            return AjaxResult.error("服务费分润比例不能高于3");
        }
        // 查询服务费分润是否高于上级代理
        String plusThreeAgent = bizUserAccountService.getPlusThreeAgentBy(useRegistrationDTO.getAccountId());
        if(plusThreeAgent != null){
            if(Double.parseDouble(useRegistrationDTO.getPlusThree()) > Double.parseDouble(plusThreeAgent)){// 高
                return AjaxResult.error("服务费分润比例不能高于上级代理:"+plusThreeAgent+",请重新设置");
            }
        }
        // 当前代理的所有下级  全部设置为当前比例
        List<BizMerchant> merchants = bizUserAccountService.getAllChildMerchantByAccountId(useRegistrationDTO.getAccountId());
        for(BizMerchant merchant : merchants){
            updateAccountPlusThree(merchant,useRegistrationDTO.getPlusThree());
        }
        return toAjax(bizUserAccountService.updateBizSetAccount(bizAgentOpenAccount));
    }

    public void updateAccountPlusThree(BizMerchant merchant,String plusThree){
        bizUserAccountService.updateAccountPlusThreeByUserId(merchant.getUserId(),plusThree);
    }

    /**
     * 删除1、统一商户入件
     */
    @PreAuthorize("@ss.hasPermi('system:entry:remove')")
    @Log(title = "1、统一商户入件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bizUserAccountService.deleteBizUserAccountByIds(ids));
    }
    public static boolean isChineseChar(char c) {
      return String.valueOf(c).matches("[\u4e00-\u9fa5]");

    }

    public static void main(String[] args) throws IOException {
       String test= DESHelperUtil.decrypt("091890e4d30e405fbffc6cf4a4cd5b99","rGeWVMfVbxM=");
        System.out.println(test);
    }


    @PostMapping("/update/rate")
    public AjaxResult updateRate(){
        return iSysUserService.updateRate();
    }
}
